<?php

namespace App\Model\Facades;

use App\Model\Entity\AdminRole;
use Illuminate\Support\Facades\DB;

class  AdminRoles extends Common
{
    static private $_interface = null;

    static public function create()
    {
        // TODO: Implement create() method.
        if (empty(self::$_interface)) {
            self::$_interface = new static();
        }
        return self::$_interface;
    }

    public function add()
    {
        // TODO: Implement add() method.
        $data = \request()->get('data');

        list($errors, $v) = $this->dataValidator($data, [
            'name' => 'required',
            'slug' => 'required|unique:admin_roles',
        ], [
            'name.required' => '角色名称不能为空',
            'slug.required' => '角色规则不能为空',
            'slug.unique' => '角色规则已经存在',
        ]);

        if (!empty($errors))
            return [$errors, $v];

        $roles = new AdminRole();
        $roles->fill($data);
        return [$roles->save(), []];

    }

    public function edit($id)
    {
        $roles = $this->show($id);

        $data = \request()->get('data');

        list($errors, $v) = $this->dataValidator($data, [
            'name' => 'required'
        ], [
            'name.required' => '角色名称不能为空'
        ]);

        if (!empty($errors))
            return [$errors, $v];

        $roles->fill($data);

        return [$roles->save(), []];
    }

    public function show($id)
    {
        $result = AdminRole::find($id);
        return $result;
    }

    public function index()
    {
        parent::index(); // TODO: Change the autogenerated stub
        return AdminRole::all();
    }

    public function delete()
    {
        parent::delete(); // TODO: Change the autogenerated stub
    }

    public function sys($id)
    {
        $data = request()->get('data');
        DB::table('admin_role_permissions')->where(['role_id' => $id])->delete();

        if (empty($data['pms']))
            return true;

        $insertArray = [];
        foreach ($data['pms'] as $key => $row) {
            $insertArray[$key]["role_id"] = $id;
            $insertArray[$key]["permission_id"] = $row;
        }
        return DB::table('admin_role_permissions')->insert($insertArray);
    }

    public function menuSys($id)
    {
        $data = request()->get('data');
        DB::table('admin_role_menus')->where(['role_id' => $id])->delete();
        if (empty($data['muen']))
            return true;

        $insertArray = [];
        foreach ($data['muen'] as $key => $row) {
            $insertArray[$key]["role_id"] = $id;
            $insertArray[$key]["menu_id"] = $row;
        }
        return DB::table('admin_role_menus')->insert($insertArray);

    }
}